<?php
use system\core\Config;
use system\core\Request;

if ( ! function_exists('base_url') )
{
    /**
     * Returns the base URL configured in the config file.
     * 
     * @param string $url
     * @return string
     */
    function base_url( $url = NULL, $module = FALSE )
    {
        if ( $module == TRUE )
        {
            $request = Request::getInstance();
        }

        if ( $url != NULL )
        {
            return ($module == TRUE ) ? Config::get('config', 'base_url') . $request->getModule() . '/' . $url
                : Config::get('config', 'base_url') . $url;
        }
        else
        {
            return Config::get('config', 'base_url');
        }
    }
}

if ( ! function_exists('current_url') )
{
    /**
     * Returns the current URL
     * 
     * @return string
     */
    function current_url()
    {
        $protocol = ( strstr($_SERVER['SERVER_PROTOCOL'], 'https') ) ? 'https' : 'http';
        return $protocol . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    }
}

if ( ! function_exists('previous_url') )
{
    /**
     * Returns the current URL
     * 
     * @return string
     */
    function previous_url()
    {
        if ( isset($_SERVER['HTTP_REFERER']) )
        {
            return $_SERVER['HTTP_REFERER'];
        }
        
        return FALSE;
    }
}

if ( ! function_exists('redirect') )
{
    /**
     * Redirect to a specific location
     * 
     * You can choose: location or refresh as type
     * 
     * @param string $location
     * @param string $type location or refresh
     */
    function redirect( $location = '', $type = 'location' )
    {
        if ( ! preg_match('#^https?://#i', $location) )
        {
            $location =  Config::get('config', 'base_url') . $location;
        }
        
        switch ( $type )
        {
            case 'refresh':
                header('Refresh: 0; url=' . $location);
            break;
            default:
                header('Location: ' . $location, TRUE);
        }
        
        die();
    }
}

/* End of file url_helper.php */